package com.bs.areport.sys.security;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import com.bs.restframework.adaptive.util.DataAdaptiveUtil;
import com.bs.restframework.context.SystemContext;
import com.bs.restframework.context.util.SystemContextUtil;
import com.bs.restframework.session.UserSession;
import com.bs.areport.sys.security.DefaultResCheck;

/**
 * <p>
 * Title:  安全体测过滤类
 * </p>
 * 
 * 
 * <p>
 * Copyright: Copyright (c) 2009
 * </p>
 * 
 * <p>
 * Company: EPay团队
 * </p>
 * 
 * <p>
 * 建立时间: 2011-06-28 上午11:22:30
 * </p>
 * 
 * @author 林光延
 * 
 * @version 1.0
 * 
 *          修订记录: 2011-06-28 上午11:22:30  林光延  建立
 * 
 */

public class TraSecurityFilter implements Filter {

	private static Logger log = LoggerFactory.getLogger(TraSecurityFilter.class);
	
	
	/**
	 * 拦截bean的名称
	 */
	protected String interceptorName = null;
	
	
	

    
	public void destroy() {

	}

	@SuppressWarnings("static-access")
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		    ((HttpServletRequest)request).setCharacterEncoding("utf-8");
		    String url = ((HttpServletRequest)request).getRequestURI();		
		    System.out.println(url);
			 String urlDot =url.substring(url.lastIndexOf(".")+1, url.length());
			if(doCheck(request,response)) 
		    	chain.doFilter((HttpServletRequest)request, (HttpServletResponse)response);
			else {
				sendView(request, response,urlDot,"LOGIN_001","您未登录系统或登录已过期<br/>请重新登录!!!");
			}   
	}

	private boolean doCheck(ServletRequest request, ServletResponse response) {
		 String url = ((HttpServletRequest)request).getRequestURI();		
		 String ip= ((HttpServletRequest)request).getRemoteAddr();
		 String token = request.getParameter("Token");
//		 System.out.println(token);
		 UserSession us = SystemContextUtil.getSessionMange().getUserSession(token);
		 String urlDot =url.substring(url.lastIndexOf(".")+1, url.length());
		 
		 log.debug("调用地址 URL: " + url);
			// 不是无需安全检查
			if (!this.noCheck(url,request,response)) {
				 if (us != null)
				 {
					log.debug("==============调用地址 URL:【{}】 =============", url);
					
					//如果用户没有登录
					if(!us.isLogin()){
//						sendView(request, response,urlDot,"LOGIN_001","您未登录系统或登录已过期<br/>请重新登录!!!");
						return false;
					}
				 }
				 else
				 {
//					sendView(request, response,urlDot,"LOGIN_001","您未登录系统或登录已过期<br/>请重新登录!!!");
					return false;
				 }
			} 
		return true;
	}

	private void sendView(ServletRequest request, ServletResponse response,String dot,String code ,String msg) {
		if(dot.equalsIgnoreCase("do") || dot.equalsIgnoreCase("file") || dot.equalsIgnoreCase("jsp")){
			sendToDefault(request,response,((HttpServletRequest)request).getContextPath()+"/",msg);
		}else if(dot.equalsIgnoreCase("json") || dot.equalsIgnoreCase("xml")||dot.equalsIgnoreCase("String")){
			writeResponse(request,response,dot,code,msg);
		}
		
	}

	private void sendToDefault(ServletRequest request, ServletResponse response,String pageName,String msg){
		try{
			((HttpServletResponse)response).sendRedirect(((HttpServletRequest)request).getContextPath()+"/");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void writeResponse(ServletRequest request,ServletResponse response,String urlDot,String code, String msg) {
		HashMap<String, Object> result2 = new HashMap<String, Object>();
		result2.put("CODE", code);
		result2.put("msg", msg);
		result2.put("tag",true);
		result2.put("isLogin",false);

		if ("json".equalsIgnoreCase(urlDot)
				|| "String".equalsIgnoreCase(urlDot)) {
			response.setContentType("text/html; charset=utf-8");
			try {

				response.getWriter().print(DataAdaptiveUtil.getDataAdaptive("json")
						.toString(result2).toString());
			} catch (IOException e) {
				log.debug("写入Response的时候出错: ", e.getMessage());
				e.printStackTrace();
			}
		} else if ("xml".equalsIgnoreCase(urlDot)) {
			response.setContentType("text/html; charset=utf-8");
			try {

				response.getWriter().print(
						DataAdaptiveUtil.getDataAdaptive("xml")
								.toString(result2).toString());
			} catch (IOException e) {
				log.debug("写入Response的时候出错: ", e.getMessage());
				e.printStackTrace();
			}
		}
		
	}

	private boolean noCheck(String url,ServletRequest request,ServletResponse response) {
		boolean result=false;
		//不检查的地址
		if(url.equals(((HttpServletRequest)request).getContextPath()+"/")
				||url.substring(url.lastIndexOf("/")+1, url.length()).equals("login.do")||
				url.substring(url.lastIndexOf("/")+1, url.length()).equals("getToken.json")||
				url.substring(url.lastIndexOf("/")+1, url.length()).equals("getValidCode.do"))
			result=true;
		return result;
	}

	/**
	 * 初始化过滤器
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.interceptorName = filterConfig.getInitParameter("beanName");
		Assert.notNull(this.interceptorName, "请先设定安全检测Spring Bean 名称");
		Assert.hasLength(this.interceptorName.trim(), "请先设定安全检测Spring Bean 名称");
	}
	
}
